;//
//  SpokenViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2017/10/26.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "HeartaxCell.h"
#define HeartaxCellIndentifier @"HeartaxCellIndentifier"
#import "HeartaxDetailController.h"
#import "CommonFunc.h"
#import "HeartaxModel.h"
#import "WShareUtil.h"
#import "HHBaseLoadToken.h"
#import "MJRefresh.h"
#import "LoginViewController.h"
#import "AudioPlayerManage.h"
#import "AppDelegate.h"
#import "PlayerModel.h"
#import "CheckNetwork.h"
#import "SpokenViewController.h"
#import "WWebViewController.h"

@interface SpokenViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,AudioPlayerManageDelegate>

{
    UIView *firstView; // Cell第一行的视图
    //数据源数组
    NSArray *_array;
    NSDictionary *dict;
    NSArray *_miniArray;
    NSArray *tempArr;
    int Acount;
    int j;
    UIView *headerView;
    BOOL isA;
    HeartaxCell *cell1;
    CGFloat cellTitH;
}

@property (nonatomic, strong)HeartaxModel *heartaxModel;
@property (nonatomic ,strong)NSString *sortStr;// 排序 参数
@property (nonatomic, strong)NSMutableArray *arrMTS;
@property (nonatomic ,strong)NSString *strbfCount;// 总播放次数
@property (nonatomic ,strong)NSString *strtotal;// 已更新期数

@end

@implementation SpokenViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.myTableView reloadData];
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"说税";
    isA = YES;
    // 1.注册控件
    UINib *cellNib = [UINib nibWithNibName:@"HeartaxCell" bundle:nil];
    [self.myTableView registerNib:cellNib forCellReuseIdentifier:HeartaxCellIndentifier];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:HeartaxCellIndentifier];

    j = 1;
    _sortStr = @"desc";
    _arrMTS = [NSMutableArray array];

    NSArray *arrReturn = [WShareUtil readModelDataFromFile:@"HeartaxList"];

    if (arrReturn != nil && arrReturn.count > 0) {
        for (NSDictionary *dic in arrReturn) {
            HeartaxModel *heartaxModel = [HeartaxModel mj_objectWithKeyValues:dic];
            [self.arrMTS addObject:heartaxModel];
        }
    }

    //申明静态变量  点击一次自增1
    Acount = 0;
    [self notifyRequestListData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToggleClick) name:PLAYTOGGLE object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noPlay) name:@"NOPLAY" object:nil];
}

- (void)noPlay {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"Toolplay"] forState:UIControlStateNormal];
    appDelegate.wWindow.playTool.btnPlay.selected = NO;
}

- (void)playToggleClick {
    [self.myTableView reloadData];
}

- (void)changeUIstateClicked:(AVPlayer *)player {

    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    //    NSString *strProgress = [NSString stringWithFormat:@"%.f",streamer.progress];
    //    NSString *strTime = [self convertStringWithTime:[strProgress floatValue]];
    //
    //    appDelegate.wWindow.playTool.lbTime.text = strTime;

    CMTime ctime = [player currentTime];
    Float64 currentSeconds = CMTimeGetSeconds(ctime);

    NSString *strProgress = [NSString stringWithFormat:@"%.2f",currentSeconds];
    appDelegate.wWindow.playTool.lbTime.text = [self convertStringWithTime:([strProgress floatValue])];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.myTableView reloadData];
    });
}

#pragma mark - 私有方法
- (NSString *)convertStringWithTime:(float)time {
    if (isnan(time)) time = 0.f;
    int min = time / 60.0;
    int sec = time - min * 60;
    NSString * minStr = min > 9 ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min];
    NSString * secStr = sec > 9 ? [NSString stringWithFormat:@"%d",sec] : [NSString stringWithFormat:@"0%d",sec];
    NSString * timeStr = [NSString stringWithFormat:@"%@:%@",minStr, secStr];
    return timeStr;
}


- (void)noWifiRefershingEnd {
    [self.myTableView.header endRefreshing];
    [self.myTableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

- (void)notifyRequestListData{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noWifiRefershingEnd) name:REFRESHINGEND object:nil];

    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [self requestRenewNum];
        [self requestListDataStrNum:@"1" isRefresh:YES];
        j = 1;
    }];

//    if (kIsHaveNetwork) //有网
//    {
        [_myTableView.header beginRefreshing];
//    } //else无网

    self.myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num isRefresh:NO];
    }];
}

- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{

    [WShareUtil sharedData].isShowWait = NO;

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strToken]) {
        HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
        [loadToken loadToken];
        loadToken.tokenBlock = ^(NSString *strToken) {
            if (![WShareUtil strNilOrEmpty:strToken]) {
                [self requestListDataStrNum:pageNum isRefresh:isRefresh];
            }else {
                WLog(@"没有token");
            }
        };
        WLog(@"%@",[WShareUtil sharedData].strToken);
    }else {
        //        NSString *uuid= @"e1e1e1";

//        NSDictionary *parametersDict = @{@"jqbh":uuid,@"token":[WShareUtil sharedData].strToken,@"pageNum":pageNum,@"pageSize":@"10",@"sort":_sortStr};
        // 字典转JSON字符串

        NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"xxfb",@"content":@{@"revert":@"paginate",@"colcode":@"ss",@"pagesize":@"10",@"pagenumber":pageNum}};
        NSString *jsonData = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

        // 加密JSON字符串
        WLog(@"加密JSON字符串的结果%@",[CommonFunc encryptWithText:jsonData]);//加密方法
        WLog(@"解密乱码后的结果%@",[CommonFunc decryptWithText:@"sZjh+Dfxf1kcn5u4bgq4g75bHbBQ6DlL2oF3ELtxXb8dkwb1w5GRyfm7huCriDvlsdsFDoOWLqzX7tt+NpCuiEApxy+2QONMEZpGLBejk+1ZPreDtd3O7Q=="]);//解密方法

        // 加密后字典参数
        NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:jsonData]};

        [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:paramsDic success:^(id responseObject) {
            NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];

            NSString *messageStr = [JsonDic objectForKey:@"message"];
            NSString *successStr= [JsonDic objectForKey:@"success"];
            // 解密请求回的数据（字典）
            [CommonFunc decryptWithText:messageStr]; 
            NSString *returnStr = [CommonFunc decryptWithText:messageStr];
            // json字符串转字典
            NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

            if ([returnDic[@"resultCode"] isEqualToString:@"EC0001"] || [returnDic[@"resultCode"] isEqualToString:@"EC0002"] ) {
                HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
                [loadToken loadToken];
                loadToken.tokenBlock = ^(NSString *strToken) {
                    if (![WShareUtil strNilOrEmpty:strToken]) {
                        [self requestListDataStrNum:pageNum isRefresh:isRefresh];
                    }else {

                        [WShareUtil showAlert:@"温馨提示" message:@"没有token"];

                        return ;

                        WLog(@"没有token");
                    }
                };

                WLog(@"%@====",[WShareUtil sharedData].strToken);
            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0005"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您的服务已经到期"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0006"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您被禁止登录"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0008"]){

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的账号可能在其他设备登录,是否要重新登录？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重新登录", nil];
                [alertView show];

                [WShareUtil sharedData].dicSession = nil;
                return ;
                WLog(@"没有用户");

            }

            if (isRefresh) {
                [self.arrMTS removeAllObjects];
            }
//            _strbfCount = [NSString stringWithFormat:@"%@",[returnDic objectForKey:@"bfCount"]];// 总播放次数
            _strtotal = [NSString stringWithFormat:@"%@",[returnDic objectForKey:@"total"]];// 已更新期数

            for (NSDictionary *dic in returnDic[@"data"]) {
                HeartaxModel *heartaxModel = [HeartaxModel mj_objectWithKeyValues:dic];
                [self.arrMTS addObject:heartaxModel];
            }

            NSMutableArray *arrMplayList = [NSMutableArray array];

            for (HeartaxModel *model in self.arrMTS) {

                NSString *strUrl = [model.audio_src stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];

                NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
                dicM[@"title"] = model.title;
                dicM[@"audio_src"] = strUrl;
                dicM[@"audio_id"] = model.ID;
                PlayerModel *playerModel = [PlayerModel mj_objectWithKeyValues:dicM];

                [arrMplayList addObject:playerModel];

            }
            [WShareUtil sharedData].arrPlayList = arrMplayList;
            [WShareUtil removeModelDataWithFile:@"HeartaxList"];
            [WShareUtil saveModelData:self.arrMTS WithFile:@"HeartaxList"];

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myTableView reloadData];
            });
            [self.myTableView.header endRefreshing];
            [self.myTableView.footer endRefreshing];
            
            if ([returnDic[@"data"] count] < 10) {
                // 拿到当前的上拉刷新控件，变为没有更多数据的状态
                [self.myTableView.footer endRefreshingWithNoMoreData];
            }

        } failure:^(NSError *error) {
            [self noWifiRefershingEnd];
            WLog(@"请求失败");
        } showProgress:YES];
    }
}

//设置UITableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        static NSString *snap=@"snap";
        UITableViewCell *cell=[tableView  dequeueReusableCellWithIdentifier:snap];
        if (cell==nil) {
            cell=[[UITableViewCell  alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:snap];
        }
        // 设置cell不可点击
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 删除重复的子控件
        [cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

        // 设置左边图片
        firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 172)];
        firstView.backgroundColor = [UIColor whiteColor];

        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(16 , 15, 113, 130)];
        UIImage *image = [UIImage imageNamed:@"tingshuibanner.png"];//初始化图像视图
        [imgView setImage:image];
        [firstView addSubview:imgView];

        // 设置“每日听税”
        UILabel *hearTitle = [[UILabel alloc]initWithFrame:CGRectMake(145, 20, 100, 20)];
        hearTitle.text = @"每日听税";
        hearTitle.textColor = [UIColor blackColor];
        hearTitle.textAlignment = NSTextAlignmentLeft;
        hearTitle.font = [UIFont systemFontOfSize:17];
        [firstView addSubview:hearTitle];

        // 设置“简介”
        UILabel *introduce = [[UILabel alloc]initWithFrame:CGRectMake(145, 55, [UIScreen mainScreen].bounds.size.width - 160, 80)];
        introduce.text = @"简介：每日给大家分享一个财税新政、财税实操或者财税策划技巧。";
        introduce.textColor = [UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1];
        introduce.textAlignment = NSTextAlignmentLeft;
        introduce.font = [UIFont systemFontOfSize:15];
        introduce.numberOfLines = 0;
        [firstView addSubview:introduce];

        //设置“播放次数”
        UILabel *number = [[UILabel alloc]initWithFrame:CGRectMake(145, 125, [UIScreen mainScreen].bounds.size.width - 160, 20)];

        if (_strbfCount == nil||[_strbfCount isEqualToString:@"null"]||[_strbfCount isEqual:[NSNull null]]) {

            number.text = @"  ";

        }else{

            number.text = [NSString stringWithFormat:@"播放：%@次",_strbfCount];
        }


        number.textColor = [UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1];
        number.textAlignment = NSTextAlignmentLeft;
        number.font = [UIFont systemFontOfSize:13];
        [firstView addSubview:number];

        // 分割线
        UILabel *lineLb = [[UILabel alloc]initWithFrame:CGRectMake(0, firstView.bounds.size.height - 12, [UIScreen mainScreen].bounds.size.width, 1)];
        lineLb.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.95 alpha:1];
        [firstView addSubview:lineLb];

        [cell addSubview:firstView];
        return cell;

    }else if (indexPath.section == 1){
        cell1  = [[[NSBundle mainBundle] loadNibNamed:@"HeartaxCell" owner:self options:nil] lastObject];

        if (self.arrMTS.count > 0 && self.arrMTS != nil) {

            cell1.titleLB.numberOfLines = 0;
            cell1.titleLB.textAlignment = NSTextAlignmentLeft;
            cell1.titleLB.text = [self.arrMTS[indexPath.row] title];
            cell1.titleLB.textColor = [UIColor blackColor];
            cell1.titleLB.font = [UIFont systemFontOfSize:16];
            CGSize maximumLbTitle = CGSizeMake(WSCREENH_WIDTH - 65, MAXFLOAT);//labelsize的最大值
            CGSize expectSize = [cell1.titleLB sizeThatFits:maximumLbTitle];
            cell1.cellTitH.constant = expectSize.height;
            cellTitH = expectSize.height;

            // ---------- 设置titleLB的行间距
            NSMutableParagraphStyle  *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyle  setLineSpacing:3];


            if ([WShareUtil strNilOrEmpty:cell1.titleLB.text]) {
                cell1.titleLB.text = @"";
            }
            NSMutableAttributedString  *setString = [[NSMutableAttributedString alloc] initWithString:cell1.titleLB.text];

            [setString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [cell1.titleLB.text length])];
            [cell1.titleLB setAttributedText:setString];// 设置Label要显示的text
            // ----------

//            cell1.createTimeLB.text = [WShareUtil timeFormat:[self.arrMTS[indexPath.row] createtime]];
            cell1.createTimeLB.text = [self.arrMTS[indexPath.row] createtime];

            if ([self.arrMTS[indexPath.row] playTimes] == nil || [[self.arrMTS[indexPath.row] playTimes] isEqual:[NSNull null]]) {

                cell1.userCountLB.text = @"  ";

            }else{

                cell1.userCountLB.text = [NSString stringWithFormat:@"%@次播放",[self.arrMTS[indexPath.row] playTimes]];
            }
        }

        cell1.cellBtnPlay.tag = indexPath.row;

        [cell1.cellBtnPlay setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];

//        AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
//
//        playerManage.delegatePlayer = self;
//
//
//        if ([WShareUtil sharedData].isPlay) {
//            if (playerManage.currentIndex == indexPath.row) {
//                [cell1.cellBtnPlay setImage:[UIImage imageNamed:@"pauseList"] forState:UIControlStateNormal];
//                cell1.cellBtnPlay.selected = YES;
//
//                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//
//                [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"pauseList"] forState:UIControlStateNormal];
//
//                appDelegate.wWindow.playTool.btnPlay.selected = YES;
//            }
//        }
//        cell1.delegate = self;
        return cell1;
    }

    return nil;
}

//- (void)btnOfPlayListClicked:(UIButton *)sender {
//
//    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//
//    // 如果已登录
//    AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
//    playerManage.currentIndex = sender.tag;
//    playerManage.currentUrl = [[WShareUtil sharedData].arrPlayList[sender.tag] audio_src];
//
//    sender.selected = !sender.selected;
//
//    if (sender.selected) {
//
//        [playerManage audioPlayerPlay];
//
//        [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"pauseList"] forState:UIControlStateNormal];
//        appDelegate.wWindow.playTool.btnPlay.selected = YES;
//
//        [appDelegate.wWindow showWindow];
//
//    }else {
//        [playerManage audioPlayerPause];
//
//        appDelegate.wWindow.playTool.btnPlay.selected = NO;
//
//        [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"Toolplay"] forState:UIControlStateNormal];
//
//        [appDelegate.wWindow dissmissWindow];
//    }
//    WLog(@"%@",appDelegate.wWindow.playTool.lbPlayTit.titleStr);
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.myTableView reloadData];
//    });
//
//}

//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if (indexPath.section == 1) {

        CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
        if (![checkNetwork isNetworkReachable]) {//没网
            return;
        } else {

            WWebViewController *webVc = [[WWebViewController alloc] init];
            webVc.strUrl = [self.arrMTS[indexPath.row] audio_src];
            webVc.strTitle = @"说税";
            [self.navigationController pushViewController:webVc animated:NO];
//            // 如果已登录
//            HeartaxDetailController *detailVC = [[HeartaxDetailController alloc]init];
//            detailVC.strUrl = [[WShareUtil sharedData].arrPlayList[indexPath.row] audio_src];
//
//            detailVC.currentIndex = indexPath.row;
//
//            // 正向传值
//            detailVC.strId = [self.arrMTS[indexPath.row] ID];
//            detailVC.hidesBottomBarWhenPushed=YES;
//            [WShareUtil sharedData].isHeartaxList = YES;
//            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

//分组个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

//列表行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return [self.arrMTS count];

    }

}

//设置行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        return 160;
    }else{
        return 50 + cellTitH;
    }

}

//设置页眉
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 页眉视图
    headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 30)];
    headerView.backgroundColor = [UIColor whiteColor];

    // 分割线
    UILabel *lineLb = [[UILabel alloc]initWithFrame:CGRectMake(0, headerView.bounds.size.height - 1, [UIScreen mainScreen].bounds.size.width, 1)];
    lineLb.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.95 alpha:1];
    [headerView addSubview:lineLb];

    NSString *strTotal;
    NSMutableAttributedString *attri;
    if (_strtotal == nil||[_strtotal isEqualToString:@"null"]||[_strtotal isEqual:[NSNull null]]) {
        strTotal = @"";
    }else{
        strTotal = [NSString stringWithFormat:@"已更新%@期",_strtotal];
        attri = [[NSMutableAttributedString alloc] initWithString:strTotal];
        // 修改富文本中的不同文字的样式
        [attri addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1 green:0.55 blue:0.18 alpha:1] range:NSMakeRange(3, strTotal.length - 4)];
        [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(3, strTotal.length - 4)];
    }
    // 已更新
    UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(13, 5, [UIScreen mainScreen].bounds.size.width, 20)];
    lb.font = [UIFont systemFontOfSize:16.0];
    lb.textColor = [UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1];
    lb.attributedText = attri;
    lb.textAlignment = NSTextAlignmentLeft;

    UIButton *paiXubtn = [UIButton buttonWithType:UIButtonTypeCustom];
    paiXubtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-100, 0, 100, 40);
    paiXubtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [paiXubtn setTitle:@"  排序" forState:UIControlStateNormal];
    [paiXubtn setTitleColor:[UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1] forState:UIControlStateNormal];
    [paiXubtn setTitleColor:[UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1] forState:UIControlStateSelected];
    if (isA) {
        [paiXubtn setImage:[UIImage imageNamed:@"sortup"] forState:UIControlStateNormal];
    }else {
        [paiXubtn setImage:[UIImage imageNamed:@"sortdown"] forState:UIControlStateNormal];
    }
    paiXubtn.tag = 890;
    [paiXubtn addTarget:self action:@selector(paiXubtn) forControlEvents:UIControlEventTouchUpInside];
//    [headerView addSubview:lb];
    //    [headerView addSubview:paiXubtn];

    return headerView;
}

//设置页眉的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    //设置第一个section的header为0
    if (section==0) {
        return 0;
    }
    else{
        return 0;
    }
}
// 排序
- (void)paiXubtn{

    isA = !isA;
    Acount ++;
    if(Acount %2 == 0 ) {

        _sortStr = @"asc";
        [self requestListDataStrNum:@"1" isRefresh:YES];

    }else if (Acount %2 == 1) {

        _sortStr = @"desc";
        [self requestListDataStrNum:@"1" isRefresh:YES];
    }

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
//        LoginViewController *loginVc = [[LoginViewController alloc]init];
//        [self presentViewController:loginVc animated:YES completion:nil];
//
//        __weak LoginViewController *loginVcSelf = loginVc;
//        loginVc.loginSesscion = ^{
//
//            [loginVcSelf dismissViewControllerAnimated:YES completion:nil];
//        };
    }
}

-(void)dealloc{
    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 百度统计
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

//    NSString* cName = [NSString stringWithFormat:@"%@",  self.title, nil];
//    [[BaiduMobStat defaultStat] pageviewStartWithName:cName];
}

// 退出页面，建议在此处添加
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    NSString* cName = [NSString stringWithFormat:@"%@", self.title, nil];
//    [[BaiduMobStat defaultStat] pageviewEndWithName:cName];
}

- (void)requestRenewNum {

    NSDictionary *parametersDict = @{@"content":@{@"revert":@"ssview"},@"mode":@"native",@"service":@"sxfw"};

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        _strbfCount = [NSString stringWithFormat:@"%@",returnDic[@"ssview"][@"view"]];// 总播放次数
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.myTableView reloadData];
        });

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:NO];
}

@end
